package com.gobo.jinghuimall.cart.interceptor;

import com.alibaba.fastjson.JSON;
import com.gobo.common.constant.AuthServerConstant;
import com.gobo.common.constant.CartConstant;
import com.gobo.common.vo.MemberResponseVo;
import com.gobo.jinghuimall.cart.entiry.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器 : 判断用户是否登陆
 *
 */
public class CartInterceptor implements HandlerInterceptor {
    /**
     * 每个线程都各自独有一个UserInfo
     */
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    /**
     * 目标方法执行之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        Object  loginUser1 = session.getAttribute(AuthServerConstant.LOGIN_USER);

        if (loginUser1 != null) {
            // 用户登录了
            MemberResponseVo memberResponseVo = new MemberResponseVo();
//            memberResponseVo.setId(Long.parseLong(login));
            userInfoTo.setUserId(3L);
        }
        // 是否有临时用户
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                // 有临时用户
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }

            }
        }
        // 如果没临时用户保存临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //如果不是临时用户
        if (!userInfoTo.getTempUser()) {
            String userKey = userInfoTo.getUserKey();
            //保存登录新账号的cookie
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userKey);
            // 30 天过期
            cookie.setMaxAge(CartConstant.COOKIES_USER_KEY_AGE);
            //设置cookie范围
            cookie.setDomain("jinghuimall.com");
            response.addCookie(cookie);
        }
    }
}
